package cn.jiangzeyin.system;

import cn.jiangzeyin.entity.IQuartzInfo;
import cn.jiangzeyin.job.JobUtil;
import cn.jiangzeyin.job.SystemJobListening;
import cn.jiangzeyin.log.JobLog;
import org.quartz.*;

import java.util.ArrayList;
import java.util.List;
import java.util.Properties;
import java.util.StringTokenizer;

/**
 * 调度基本管理
 * <p>
 * Created by jiangzeyin on 2017/2/13.
 *
 * @author jiangzeyin
 */
public class SystemJobManager {

    private SystemJobManager() {
    }

    private static Properties properties;

    public static String getValue(String key) {
        return getValue(key, null);
    }

    public static String getValue(String key, String def) {
        if (properties == null) {
            return null;
        }
        return properties.getProperty(key, def);
    }

    public static class RunData {
        private static String keyName;
        private static String valueName;

        public static String getValueName() {
            return valueName;
        }

        public static String getKeyName() {
            return keyName;
        }
    }

    /**
     * 加载调度信息
     *
     * @param quartzInfoList list
     * @param properties     p
     * @throws SchedulerException 异常
     * @author jiangzeyin
     */
    public static void init(List<IQuartzInfo> quartzInfoList, Properties properties) throws SchedulerException {
        if (properties == null) {
            throw new IllegalArgumentException("properties is null");
        }
        if (SystemJobManager.properties != null) {
            throw new RuntimeException("job is Initialize");
        }
        SystemJobManager.properties = properties;
        //
        RunData.keyName = getValue(JobPropertiesInfo.RUN_DATA_KEY_NAME);
        if (RunData.keyName == null || RunData.keyName.isEmpty()) {
            JobLog.getInstance().warn("please se " + JobPropertiesInfo.RUN_DATA_KEY_NAME);
        }
        //
        RunData.valueName = getValue(JobPropertiesInfo.RUN_DATA_VALUE_NAME);
        if (RunData.valueName == null || RunData.valueName.isEmpty()) {
            JobLog.getInstance().warn("please se " + JobPropertiesInfo.RUN_DATA_VALUE_NAME);
        }
        if (quartzInfoList == null || quartzInfoList.size() <= 0) {
            JobLog.getInstance().info("调度信息为空");
        } else {
            for (IQuartzInfo quartz : quartzInfoList) {
                try {
                    JobUtil.addQuartz(quartz);
                } catch (Exception e) {
                    JobLog.getInstance().error("加载：" + quartz.getName() + "调度异常", e);
                }
            }
        }
        {// 对系统运行的一些检查
            JobLog.getInstance().info("初始化系统调度信息");
            Trigger trigger_def = JobUtil.getTrigger("system", "system_trigger_listening");
            if (trigger_def != null) {
                JobLog.getInstance().info("系统调度信息已经存在");
            } else {
                JobDetail job = JobBuilder.newJob(SystemJobListening.class)
                        .withIdentity("system_job_listening", "system")
                        .build();
                // 添加调度信息
                job.getJobDataMap().put("name", "系统监听调度");
                job.getJobDataMap().put("id", -1);

                String cron = getValue(JobPropertiesInfo.SYSTEM_DETECTION_CRON, JobPropertiesInfo.SYSTEM_DETECTION_CRON_DEFAULT_VALUE);
                assert cron != null;
                CronTrigger trigger = TriggerBuilder.newTrigger()
                        .withIdentity("system_trigger_listening", "system")
                        .withSchedule(CronScheduleBuilder.cronSchedule(cron)).build();
                JobUtil.getScheduler().scheduleJob(job, trigger);
            }
        }
        String debug = getValue(JobPropertiesInfo.DEBUG, "");
        if (debug != null && !debug.isEmpty()) {
            JobLog.getInstance().info("调试模式：" + debug);
        }
        // 开启调度
        JobUtil.getScheduler().start();
    }

    /**
     * 调试模式信息
     */
    private static String debugStr;
    private static List<String> deBugList;

    private static String standAlone;
    private static List<String> standAloneList;


    /**
     * 判断是否为debug 模式
     *
     * @return true debug 模式
     */
    public static boolean isDebug() {
        return debugStr != null && !debugStr.isEmpty();
    }

    /**
     * 获取调试字符串
     *
     * @return debug 信息
     */
    public static String getDebugInfo() {
        if (debugStr == null) {
            debugStr = SystemJobManager.getValue(JobPropertiesInfo.DEBUG, "");
        }
        return debugStr;
    }

    /**
     * 获取需要调试的key
     *
     * @return list
     */
    public static List<String> getDeBugList() {
        if (deBugList != null) {
            return deBugList;
        }
        String debug = getDebugInfo();
        if (debug == null) {
            return null;
        }
        deBugList = new ArrayList<>();
        StringTokenizer st = new StringTokenizer(debug, ",");
        while (st.hasMoreTokens()) {
            String item = st.nextToken();
            deBugList.add(item.trim());
        }
        return deBugList;
    }

    /**
     * 单机运行模式
     *
     * @return 单机信息
     */
    public static List<String> getStandAloneList() {
        if (standAloneList != null) {
            return standAloneList;
        }
        if (standAlone == null) {
            standAlone = SystemJobManager.getValue(JobPropertiesInfo.STAND_ALONE, "");
        }
        if (standAlone != null && !standAlone.isEmpty()) {
            standAloneList = new ArrayList<>();
            StringTokenizer st = new StringTokenizer(standAlone, ",");
            while (st.hasMoreTokens()) {
                String item = st.nextToken();
                standAloneList.add(item.trim());
            }
        }
        return standAloneList;
    }
}
